package com.jjshop.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Colin on 2015/11/25.
 */
public class StringUtil {
    /***
     * Toast
     *
     * @param mContext
     * @param content
     */
    public static void showToast(Context mContext, String content) {
        Toast.makeText(mContext, content, Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断该文件是否是一个图片。
     */
    public static boolean isImage(String fileName) {
        return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png");
    }

    /**
     * 判断SD卡是否可用
     */
    public static boolean isSDcardOK() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }



    private static ProgressDialog progressDialog;

    /**
     * 打开提示框
     *
     * @param activity
     * @param msg
     */
    public static void showDialog(Activity activity, String msg) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(activity);
            progressDialog.setMessage(msg);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
    }

    /**
     * 关闭提示框
     */
    public static void closeDialog() {
        try {
            if (progressDialog != null) {
                progressDialog.cancel();
                progressDialog = null;
                System.gc();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 强制隐藏键盘
     *
     * @param v
     */
    public static void HideKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    /***
     * 显示虚拟键盘
     *
     * @param v
     */
    public static void ShowKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
    }


    /***
     * 解决TextView错乱问题
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }


    /***
     * 图片转Base64
     *
     * @param imageData
     * @return
     */
    public static String translate(byte[] imageData) {
        String body = Base64.encodeToString(imageData, Base64.DEFAULT);
        return body;
    }

    /***
     * Base64转图片
     *
     * @param body
     * @return
     */
    public static Bitmap getImage(String body) {
        byte[] imageData = Base64.decode(body, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
        return bitmap;
    }

    /**
     * bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getDate() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//可以方便地修改日期格式
        String dateText = dateFormat.format(date);
        return dateText;
    }

    /**
     * 获得格式化之后的系统时间
     *
     * @return
     */
    public static String formatSystemTime() {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(new Date());
    }

    /**
     * 将滴答.mp3转为滴答
     *
     * @param audioName
     * @return
     */
    public static String formatAudioName(String audioName) {
        return audioName.substring(0, audioName.lastIndexOf("."));
    }

    /***
     * 字符串非空验证
     *
     * @param result
     * @return
     */
    public static boolean isNull(String result) {
        if (result == null || "".equals(result) || result.length() <= 0 || result.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }


    public static String toNum(int num) {
        return num + "";
    }

    /**
     * 打开Activity
     *
     * @param activity
     * @param cls
     */
    public static void startActivity(Activity activity, Class<?> cls) {
        Intent intent = new Intent(activity, cls);
        intent.setClass(activity, cls);
        activity.startActivity(intent);
//        activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

    }

    /**
     * 返回当前程序版本
     */
    public static int getAppVersionCode(Context context) {
        int versionCode = 0;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionCode = pi.versionCode;
            if (versionCode == 0) {
                return 0;
            }

        } catch (Exception e) {
            LogUtil.e("VersionInfo");
        }
        return versionCode;
    }

    /**
     * 返回当前程序版本
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null) {
                return "";
            }

        } catch (Exception e) {
            LogUtil.e("VersionInfo");
        }
        return versionName;
    }

    public static String GMTime(int time) {
        long times = time * 1000;
        LogUtil.e("timeFors:" + times);
        Date nowTime = new Date(times);
        LogUtil.e("timeFor:" + time);
        LogUtil.e("timeFornow:" + System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        return retStrFormatNowDate;
    }


    public static String transEndoing(Context context, String urlStr) {
        try {
            urlStr = java.net.URLEncoder.encode(PreUtils.getString(context, "_uauth", ""), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urlStr;
    }


    /**
     * byte(字节)根据长度转成kb(千字节)和mb(兆字节)
     *
     * @param bytes
     * @return
     */
    public static String bytesToM(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
//        if (returnValue > 1)
        return (returnValue + "M");
//        BigDecimal kilobyte = new BigDecimal(1024);
//        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
//                .floatValue();
//        return (returnValue + "KB");
    }


    //对string进行转码
    public static String encodeHeadInfo(String headInfo) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0, length = headInfo.length(); i < length; i++) {
            char c = headInfo.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                stringBuffer.append(String.format("\\u%04x", (int) c));
            } else {
                stringBuffer.append(c);
            }
        }
        return stringBuffer.toString();
    }


    /***
     * MD5加密
     *
     * @param plainText
     * @return
     */
    public static String textToMD5L32(String plainText) {
        String result = null;
        //首先判断是否为空
        if (isNull(plainText)) {
            return null;
        }
        try {
            //首先进行实例化和初始化
            MessageDigest md = MessageDigest.getInstance("MD5");
            //得到一个操作系统默认的字节编码格式的字节数组
            byte[] btInput = plainText.getBytes();
            //对得到的字节数组进行处理
            md.update(btInput);
            //进行哈希计算并返回结果
            byte[] btResult = md.digest();
            //进行哈希计算后得到的数据的长度
            StringBuffer sb = new StringBuffer();
            for (byte b : btResult) {
                int bt = b & 0xff;
                if (bt < 16) {
                    sb.append(0);
                }
                sb.append(Integer.toHexString(bt));
            }
            result = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    //app uri keywords
    public static String getWord(String url) {
        String word = null;
        Pattern p = Pattern.compile("999d://(.*).app");
        Matcher m = p.matcher(url);
        while (m.find()) {
            word = m.group(1);
        }
        return word;
    }

    //download url keywords
    public static String getDownloadName(String url) {
        String word = null;

        Matcher m = Pattern.compile("[^/\\\\]+$").matcher(url);
        if (m.find()) {
            word = url.substring(m.start(), m.end()).replace("/", "");
        }

        return word;

    }

    /**
     * 关键字高亮显示 不支持中文字符
     *     **************************不能出现*等特殊符号。这是正则表达式******************************
     * @param text   需要显示的文字
     * @param target 需要高亮的关键字
     * @return spannable 处理完后的结果，记得不要toString()，否则没有效果
     */
    public static SpannableStringBuilder highlight(String text, String target) {
        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
        CharacterStyle span = null;

        Pattern p = Pattern.compile(target);
        Matcher m = p.matcher(text);
        while (m.find()) {
            span = new ForegroundColorSpan(Color.parseColor("#d70051"));// 需要重复！
            spannable.setSpan(span, m.start(), m.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannable;
    }

    /**
     * 关键字高亮显示
     *     **************************不能出现*等特殊符号。这是正则表达式******************************
     * @param text   需要显示的文字
     * @param target 需要高亮的关键字
     * @return spannable 处理完后的结果，记得不要toString()，否则没有效果
     */
    public static SpannableStringBuilder highlight(String text, String target, int color) {
        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
        CharacterStyle span = null;

        Pattern p = Pattern.compile(target);
        Matcher m = p.matcher(text);
        while (m.find()) {
            span = new ForegroundColorSpan(color);// 需要重复！
            spannable.setSpan(span, m.start(), m.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannable;
    }


    /**
     * 关键字高亮显示
     *
     * @param text   需要显示的文字
     * @param target 需要高亮的关键字
     * @return spannable 处理完后的结果，记得不要toString()，否则没有效果
     */
    public static SpannableStringBuilder changeTextColor(String text, String target, int color) {
        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
        CharacterStyle span = null;
        int index = text.indexOf(target);
        if (index != -1){
            span = new ForegroundColorSpan(color);// 需要重复！
            spannable.setSpan(span,index , index + target.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
//        Pattern p = Pattern.compile(target);
//        Matcher m = p.matcher(text);
//        while (m.find()) {
//            span = new ForegroundColorSpan(color);// 需要重复！
//            spannable.setSpan(span, m.start(), m.end(),
//                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        }
        return spannable;
    }

    /***
     * 数组转化成字符串拼接
     *
     * @param ig
     * @return
     */
    public static String converToString(long[] ig) {
        String str = "";
        if (ig != null && ig.length > 0) {
            for (int i = 0; i < ig.length; i++) {
                str += ig[i] + ",";
            }
        }
        str = str.substring(0, str.length() - 1);
        return str;
    }


    /**
     * @Description:把list转换为一个用逗号分隔的字符串
     */
    public static String listToString(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + ",");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    /***
     * 是否包含某个字符串
     *
     * @param string
     * @param keyWord
     * @return
     */
    public static boolean isContain(String string, String keyWord) {
        if (string.indexOf(keyWord) != -1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 从asset路径下读取对应文件转String输出
     *
     * @param mContext
     * @return
     */
    public static String getJson(Context mContext, String fileName) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder();
        AssetManager am = mContext.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sb.delete(0, sb.length());
        }
        return sb.toString().trim();
    }

    /***
     * 判断是否群主
     *
     * @return
     */
    public static boolean isGroupOwner(Context context) {
        if (PreUtils.getInt(context, PreUtils.ROLE_ID, 0) == 30) return true;
        else return false;
    }

    /***
     * 判断是否为群成员
     *
     * @return
     */
    public static boolean isGroupUser(String teamId, Context context) {
        if (!teamId.equals(PreUtils.getString(context, "team_id", "")))
            return false;
        else return true;
    }

    /***
     * 判断自己是否已有舞队
     *
     * @param context
     * @return
     */
    public static boolean isTeamUser(Context context) {
        if (isNull(PreUtils.getString(context, "team_id", "")))
            return false;
        else return true;
    }

    /**
     * 判断对象或对象数组中每一个对象是否为空: 对象为null，字符序列长度为0，集合类、Map为empty
     *
     * @param obj
     * @return
     */
    public static boolean isNullOrEmpty(Object obj) {
        if (obj == null)
            return true;

        if (obj instanceof CharSequence)
            return ((CharSequence) obj).length() == 0;

        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();

        if (obj instanceof Map)
            return ((Map) obj).isEmpty();

        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNullOrEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }

    public static String getTime() {
        return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(new Date());
    }


    public static void downloadImage(String downloadPath, final Context mContext) {
        HttpUtils utils = new HttpUtils();
        final String fileName = System.currentTimeMillis() + "jj.png";
        final String apkPath = GlobalContanst.DWONLOAD_IMG_PATH + fileName;
        final HttpHandler handler = utils.download(downloadPath, apkPath,
                false, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        StringUtil.showToast(mContext, "已保存到相册");
                        try {
                            MediaStore.Images.Media.insertImage(mContext.getContentResolver(), responseInfo.result.getAbsolutePath(), fileName, fileName);
                            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(apkPath)));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        StringUtil.showToast(mContext, "保存失败");
                    }
                });
    }

}
